package com.zhaoning.znojcodesandbox.utils;

import com.zhaoning.znojcodesandbox.model.ExecuteMessage;
import org.springframework.util.StopWatch;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * @Description
 * @Author zhaoning
 * @Date 2025/3/8
 */
public class ProcessUtil {
    public static ExecuteMessage runAndGetOutput(Process process, String opMessage) throws Exception {

        ExecuteMessage executeMessage = new ExecuteMessage();
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        int exitCode = process.waitFor();
        stopWatch.stop();
        executeMessage.setTime(stopWatch.getLastTaskTimeMillis());

        executeMessage.setExitCode(exitCode);

        System.out.println("执行时间：" + stopWatch.getLastTaskTimeMillis() + "ms");

        // 逐行获取信息
        BufferedReader bf;
        String line;
        if (exitCode != 0) {
            bf = new BufferedReader(new InputStreamReader(process.getErrorStream()));
        } else {
            bf = new BufferedReader(new InputStreamReader(process.getInputStream()));
        }
        StringBuilder sb = new StringBuilder();
        while ((line = bf.readLine()) != null) {
            sb.append(line);
        }
        executeMessage.setMessage(sb.toString());
        return executeMessage;
    }
}
